<template>
  <div class="page">
    <navigate>问卷答题</navigate>
    <div class="content_box">
      <div class="answer_area">
        <div class="tit">{{ info.name }}</div>
        <div class="num">
          共{{ questionList.length }}题/满分{{ info.total_score }}分
        </div>
        <!-- 显示已用时间 -->
        <div class="line"></div>
        <!-- 动态渲染当前题目 -->
        <div v-if="currentQuestion" class="answer_cont">
          <div class="type">
            {{ currentQuestionIndex + 1 }}、【{{
              getTypeName(currentQuestion.type)
            }}】（{{ currentQuestion.score }}分）
          </div>
          <div class="title" v-html="currentQuestion.content"></div>
          <div class="answer_options">
            <!-- 单选题 -->
            <div v-if="currentQuestion.type === 1">
              <div
                class="option_item cursor-pointer"
                v-for="(answer, aIndex) in currentQuestion.answer"
                :key="aIndex"
                :class="{ 'bg-selected': selectedAnswer === aIndex }"
                @click="selectAnswer(aIndex)"
              >
                {{ getOptionLetter(aIndex) }}、{{ answer.name }}
              </div>
            </div>
            <!-- 多选题 -->
            <div v-else-if="currentQuestion.type === 2">
              <div
                class="option_item dis_flex just_center_space cursor-pointer"
                v-for="(answer, aIndex) in currentQuestion.answer"
                :key="aIndex"
                @click="toggleMultiAnswer(aIndex)"
              >
                <div>{{ getOptionLetter(aIndex) }}、{{ answer.name }}</div>
                <img
                  :src="
                    isMultiAnswerSelected(aIndex) ? activeIcon : inactiveIcon
                  "
                  alt=""
                  class="checkbox_img"
                />
              </div>
            </div>
            <!-- 填空题 -->
            <div v-else-if="currentQuestion.type === 3">
              <div
                class="multiple_choice_item dis_flex"
                v-for="(answer, aIndex) in currentQuestion.answer"
                :key="aIndex"
              >
                <span>填空{{ aIndex + 1 }}：</span>
                <input
                  type="text"
                  class="option_item"
                  placeholder="请输入你的答案"
                  :value="fillAnswers[aIndex]"
                  @input="updateFillAnswer(aIndex, $event.target.value)"
                />
              </div>
            </div>
            <!-- 判断题 -->
            <div v-else-if="currentQuestion.type === 4">
              <div
                class="option_item cursor-pointer"
                v-for="(answer, aIndex) in currentQuestion.answer"
                :key="aIndex"
                :class="{ 'bg-selected': selectedAnswer === aIndex }"
                @click="selectAnswer(aIndex)"
              >
                {{ getOptionLetter(aIndex) }}、{{ answer.name }}
              </div>
            </div>
            <!-- 问答题 -->
            <div v-else-if="currentQuestion.type === 5">
              <textarea
                name=""
                id=""
                placeholder="请输入你的答案"
                :value="essayAnswer"
                @input="updateEssayAnswer($event.target.value)"
              ></textarea>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="btn btn_01" @click="next" :disabled="isLastQuestion">
      {{ isLastQuestion ? "提交答案" : "下一题" }}
    </div>
    <div class="btn btn_02" @click="prev" :disabled="isFirstQuestion">
      上一题
    </div>
  </div>
</template>

<script>
import { queryQnPaperInfo, subQnAnswer } from "@/api/evaluation/questionnaire";

export default {
  data() {
    return {
      activeIcon: require("@/assets/images/common/checkbox11.png"),
      inactiveIcon: require("@/assets/images/common/checkbox1.png"),
      id: "",
      taskId: "",
      info: {},
      questionList: [],
      currentQuestionIndex: 0,
      answers: [], // 存储所有问题的答案
      startTime: null, // 开始时间戳
      timer: null, // 计时器
      usedTime: 0, // 已用时间（秒）
    };
  },
  computed: {
    // 当前显示的问题
    currentQuestion() {
      return this.questionList[this.currentQuestionIndex];
    },
    // 是否是第一个问题
    isFirstQuestion() {
      return this.currentQuestionIndex === 0;
    },
    // 是否是最后一个问题
    isLastQuestion() {
      return this.currentQuestionIndex === this.questionList.length - 1;
    },
    // 单选题/判断题的当前选中答案
    selectedAnswer() {
      if (!this.currentQuestion) return null;
      return this.answers[this.currentQuestionIndex]?.selectedAnswer ?? null;
    },
    // 多选题的当前选中答案
    multiAnswers() {
      if (!this.currentQuestion) return [];
      return this.answers[this.currentQuestionIndex]?.multiAnswers ?? [];
    },
    // 填空题的当前答案
    fillAnswers() {
      if (!this.currentQuestion) return [];
      return this.answers[this.currentQuestionIndex]?.fillAnswers ?? [];
    },
    // 问答题的当前答案
    essayAnswer() {
      if (!this.currentQuestion) return "";
      return this.answers[this.currentQuestionIndex]?.essayAnswer ?? "";
    },
    // 检查是否所有问题都已回答
    allQuestionsAnswered() {
      return this.questionList.every((question, index) => {
        const answer = this.answers[index];
        if (!answer) return false;

        switch (question.type) {
          case 1: // 单选题
          case 4: // 判断题
            return (
              answer.selectedAnswer !== undefined &&
              answer.selectedAnswer !== null
            );
          case 2: // 多选题
            return answer.multiAnswers && answer.multiAnswers.length > 0;
          case 3: // 填空题
            return (
              answer.fillAnswers &&
              answer.fillAnswers.length === question.answer.length &&
              answer.fillAnswers.every((ans) => ans.trim() !== "")
            );
          case 5: // 问答题
            return answer.essayAnswer && answer.essayAnswer.trim() !== "";
          default:
            return false;
        }
      });
    },
  },
  created() {
    this.id = this.$route.query.id;
    this.taskId = this.$route.query.taskId;
    this.startTime = Date.now(); // 记录开始时间
    this.startTimer(); // 开始计时
    this.getQnPaperInfo();
  },
  beforeDestroy() {
    // 组件销毁前清除计时器
    this.clearTimer();
  },
  methods: {
    // 开始计时器
    startTimer() {
      this.timer = setInterval(() => {
        this.usedTime = Math.floor((Date.now() - this.startTime) / 1000);
      }, 1000);
    },

    // 清除计时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // 格式化时间显示
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
        .toString()
        .padStart(2, "0")}`;
    },

    async getQnPaperInfo() {
      const res = await queryQnPaperInfo({ id: this.id });
      if (res.code == 200) {
        this.questionList = res.data.topic;
        this.info = {
          name: res.data.name,
          total_score: res.data.total_score,
        };

        // 初始化答案数组，为所有题型创建适当的结构
        this.answers = this.questionList.map((question) => {
          const answer = {};

          switch (question.type) {
            case 3: // 填空题
              answer.fillAnswers = this.createReactiveArray(
                question.answer?.length || 0,
                ""
              );
              break;
            case 1: // 单选题
            case 4: // 判断题
              answer.selectedAnswer = null; // 初始化为null表示未选择
              break;
            case 2: // 多选题
              answer.multiAnswers = []; // 初始化为空数组
              break;
            case 5: // 问答题
              answer.essayAnswer = ""; // 初始化为空字符串
              break;
          }

          return answer;
        });
      }
    },
    // 创建响应式数组
    createReactiveArray(length, initialValue) {
      const arr = [];
      for (let i = 0; i < length; i++) {
        arr.push(initialValue);
      }
      return arr;
    },
    // 获取题型名称
    getTypeName(type) {
      const typeMap = {
        1: "单选题",
        2: "多选题",
        3: "填空题",
        4: "判断题",
        5: "问答题",
      };
      return typeMap[type] || "";
    },
    // 获取选项字母
    getOptionLetter(index) {
      return String.fromCharCode(65 + index);
    },
    // 选择单选题/判断题答案
    selectAnswer(index) {
      // 确保答案对象存在
      if (!this.answers[this.currentQuestionIndex]) {
        this.$set(this.answers, this.currentQuestionIndex, {});
      }

      this.$set(
        this.answers[this.currentQuestionIndex],
        "selectedAnswer",
        index
      );
    },
    // 切换多选题答案
    toggleMultiAnswer(index) {
      // 确保答案对象存在
      if (!this.answers[this.currentQuestionIndex]) {
        this.$set(this.answers, this.currentQuestionIndex, {});
      }

      const currentAnswers = [...this.multiAnswers];
      const answerIndex = currentAnswers.indexOf(index);

      if (answerIndex > -1) {
        currentAnswers.splice(answerIndex, 1);
      } else {
        currentAnswers.push(index);
      }

      this.$set(
        this.answers[this.currentQuestionIndex],
        "multiAnswers",
        currentAnswers
      );
    },
    // 检查多选题选项是否被选中
    isMultiAnswerSelected(index) {
      return this.multiAnswers.includes(index);
    },
    // 更新填空题答案
    updateFillAnswer(index, value) {
      // 确保答案对象存在
      if (!this.answers[this.currentQuestionIndex]) {
        this.$set(this.answers, this.currentQuestionIndex, {});
      }

      // 确保fillAnswers数组存在
      if (!this.answers[this.currentQuestionIndex].fillAnswers) {
        this.$set(
          this.answers[this.currentQuestionIndex],
          "fillAnswers",
          this.createReactiveArray(this.currentQuestion.answer.length, "")
        );
      }

      // 更新特定索引的填空答案
      this.$set(
        this.answers[this.currentQuestionIndex].fillAnswers,
        index,
        value
      );
    },
    // 更新问答题答案
    updateEssayAnswer(value) {
      // 确保答案对象存在
      if (!this.answers[this.currentQuestionIndex]) {
        this.$set(this.answers, this.currentQuestionIndex, {});
      }

      this.$set(this.answers[this.currentQuestionIndex], "essayAnswer", value);
    },
    // 下一题
    next() {
      if (this.isLastQuestion) {
        // 提交答案逻辑
        this.submitAnswers();
      } else {
        this.currentQuestionIndex++;
      }
    },
    // 上一题
    prev() {
      if (!this.isFirstQuestion) {
        this.currentQuestionIndex--;
      }
    },
    async submitAnswers() {
      if (!this.allQuestionsAnswered) {
        this.$toast.fail("请回答所有问题");
        return;
      }

      // 清除计时器
      this.clearTimer();

      // 处理答案数据
      const formattedAnswers = this.questionList.map((question, index) => {
        const answer = this.answers[index];
        let result;

        switch (question.type) {
          case 1: // 单选题
          case 4: // 判断题
            // 修改为通过索引获取选项ID
            result =
              answer.selectedAnswer !== null
                ? question.answer[answer.selectedAnswer].id
                : null;
            break;
          case 2: // 多选题
            // 通过索引数组获取选项ID数组
            result = answer.multiAnswers.map(
              (aIndex) => question.answer[aIndex].id
            );
            break;
          case 3: // 填空题
            result = answer.fillAnswers;
            break;
          case 5: // 问答题
            result = answer.essayAnswer;
            break;
          default:
            result = null;
        }

        return {
          topic_id: question.id, // 修改为 topic_id
          type: question.type, // 添加 type 字段
          answer: result,
        };
      });

      // 提交答案，包含用时
      let par = {
        id: this.taskId,
        question_answer: formattedAnswers,
        finish_used_time: this.usedTime, // 提交实际用时
      };
      let res = await subQnAnswer(par);
      if (res.code === 200) {
        this.$toast.success("提交成功");
        this.$router.push("/nav/evaluate");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.dis_flex {
  display: flex;
  align-items: center;
}
.just_center_space {
  justify-content: space-between;
}
.page {
  background: #f4f6fa;
  color: #333333;
}
.content_box {
  padding: 10px;
}
.answer_area {
  background: #ffffff;
  border-radius: 6.67px;
  padding-top: 16.33px;
}
.tit {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.num {
  color: #888888;
  font-size: 14px;
  margin: 16.33px 0;
  text-align: center;
}
.line {
  width: 100%;
  border-bottom: 1px solid #bfbfbf;
}
.answer_cont {
  margin-top: 18.67px;
  padding: 20px 10px;
}
.type,
.title {
  font-size: 15.33px;
}
.title {
  margin: 21px 0 26px;
}
:deep(.title input) {
  border: none;
  outline: none;
  text-align: center;
  border-bottom: 1px solid #000;
}
.answer_options {
  margin-top: 16px;
}

.option_item {
  width: 100%;
  height: 46.67px;
  line-height: 46.57px;
  background: #f7f7f7;
  border-radius: 6.67px;
  font-size: 14.67px;
  margin-bottom: 13.33px;
  padding: 0 10px;
  box-sizing: border-box;
  &:last-child {
    margin-bottom: 0;
  }
}
.bg-selected {
  background: rgba(0, 174, 255, 0.2);
  color: #333;
}
.multiple_choice_item {
  margin-bottom: 13.33px;
  &:last-child {
    margin-bottom: 0;
  }
  span {
    font-size: 14px;
    margin-right: 19px;
  }
  input {
    width: 70%;
    border: 0;
  }
}
textarea {
  width: 100%;
  height: 250px;
  background: #f4f6fa;
  border-radius: 6.67px;
  padding: 14px;
  font-size: 14px;
  box-sizing: border-box;
  border: 0;
}
.btn {
  width: 333.33px;
  height: 46.67px;
  line-height: 46.67px;
  margin: 20px auto 0;
  text-align: center;
  background: linear-gradient(0deg, #ffffff -20%, rgba(255, 255, 255, 0) 20%),
    #0aa7f4;
  border-radius: 6.67px;
  font-size: 15.33px;
}
.btn_01 {
}
.btn_02 {
  background: #ffffff;
  color: #333;
}
.checkbox_img {
  width: 14.67px;
  height: 14.67px;
}
</style>
